package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.BuyInfoBean;
import com.project.bean.BuyOrderBean;
import com.project.bean.ProductBean;
import com.project.mapper.IBuyInfoMapper;
import com.project.mapper.IBuyOrderMapper;
import com.project.mapper.IProductMapper;
import com.project.service.IBuyInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class BuyInfoService implements IBuyInfoService {
    @Autowired
    private IBuyOrderMapper buyOrderMapper;
    @Autowired
    private IProductMapper productMapper;
    @Autowired
    private IBuyInfoMapper buyInfoMapper;
    @Override
    public IPage<BuyOrderBean> findByItem(Integer pageNO, String supplierName, LocalDate startDate, LocalDate endDate) {
        QueryWrapper<BuyOrderBean> qw = new QueryWrapper<>();
        IPage<BuyOrderBean> page = new Page<>(pageNO, 3);
        if (supplierName!= null && !supplierName.equals("")) {
            qw.like("bo_supplierName", supplierName);
        }
        if (startDate != null){
            qw.ge("bo_date", startDate);
        }
        if (endDate!= null){
            qw.le("bo_date", endDate);
        }
        return buyOrderMapper.selectPage(page,qw);
    }

    @Override
    public BuyOrderBean findByOrderId(Integer buyOrderId) {
        BuyOrderBean buyOrderBean = buyOrderMapper.selectById(buyOrderId);

        QueryWrapper<BuyInfoBean> qw = new QueryWrapper<>();
        qw.eq("fk_buyOrderId", buyOrderId);
        List<BuyInfoBean> list = buyInfoMapper.selectList(qw);
        for (BuyInfoBean buyInfoBean : list) {
            ProductBean productBean = productMapper.selectById(buyInfoBean.getProductId());
            buyInfoBean.setProductBeanInBuyInfo(productBean);
            buyInfoMapper.updateById(buyInfoBean);
        }

        buyOrderBean.setBuyInfoBeanList(list);
        return buyOrderBean;
    }
}
